<template>
  <view v-if="shopPopup.selectShop.id" class="container" :style="appThemeStyle">
    <view class="header" @click.stop="handlePopupVisible(true)">
      <view class="oneline-hide">{{ shopPopup.selectShop.shopName }}</view>
      <view v-if="shopPopup.shopList && shopPopup.shopList.length" class="iconfont">&#xe6ac;</view>
    </view>
    <view v-if="onlineFirst.content" class="card">
      <view class="header">
        <view class="title">首条消息1分钟自动回复</view>
        <u-switch
            v-model="onlineFirst.status"
            size="30"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange($event, editModalType.ONLINE_FIRST)"
        />
      </view>
      <view class="content">
        <view class="text">{{ onlineFirst.content }}</view>
        <view class="action">
          <view @click.stop="handleEditModalVisible(true, editModalType.ONLINE_FIRST)">
            <text class="iconfont">&#xe6b6;</text>
            <text>编辑</text>
          </view>
        </view>
      </view>
    </view>
    <view v-if="busy.content" class="card">
      <view class="header">
        <view class="title">忙碌状态自动回复</view>
        <u-switch
            v-model="busy.status"
            size="30"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange($event, editModalType.BUSY)"
        />
      </view>
      <view class="content">
        <view class="text">{{ busy.content }}</view>
        <view class="action">
          <view @click.stop="handleEditModalVisible(true, editModalType.BUSY)">
            <text class="iconfont">&#xe6b6;</text>
            <text>编辑</text>
          </view>
        </view>
      </view>
    </view>

    <u-popup
        v-model="shopPopup.show"
        mode="bottom"
        closeable
        safe-area-inset-bottom
        :border-radius="24"
        @close="handlePopupVisible(false)"
    >
      <view class="shops-popup">
        <view class="header">
          <text>选择门店</text>
        </view>
        <view class="search">
          <view class="iconfont">&#xe6a2;</view>
          <input
              v-model="shopPopup.searchValue"
              placeholder="输入门店名称"
              placeholder-style="color: #999999; font-size: 28rpx; line-height: 40rpx"
              confirm-type="search"
              @confirm="search"
          />
        </view>
        <scroll-view scroll-y class="content">
          <view
              v-for="shop in shopPopup.shopList"
              :key="shop.id"
              class="shop-item"
              :style="[{ color: shop.id === shopPopup.selectShop.id ? '#2D71FD' : '#333333' }]"
              @click.stop="getShopConfig(shop)"
          >{{ shop.shopName }}</view>
        </scroll-view>
      </view>
    </u-popup>

    <!-- 编辑自动回复 -->
    <u-modal
        v-model="editModal.visible"
        :title="`${editModal.type === editModalType.ONLINE_FIRST ? '首条消息1分钟自动回复' : '忙碌状态自动回复'}`"
        :width="560"
        :negative-top="320"
        show-cancel-button
        @confirm="handleEditModalConfirm"
        @cancel="handleEditModalVisible(false)"
    >
      <view class="edit-modal">
        <textarea
            v-model="editModal.content"
            placeholder="请输入"
            :adjust-position="false"
            :maxlength="50"
            :cursor-spacing="200"
            :cursor="50"
            :show-confirm-bar="false"
            placeholder-style="font-size: 30rpx; color: #CCCCCC"
        />
        <view>最多可输入50个字</view>
      </view>
    </u-modal>
  </view>
</template>

<script>
import store from "@/store";
import { getShopsAutoReplyConfig, saveShopsAutoReplyConfig } from "@/api/message/settings";
// 首条消息1分钟自动回复默认文案
const onlineFirstDefault = '亲爱的顾客，欢迎光临小店。目前客服繁忙，回复可能有延时，如急需帮助，请拨打店内电话。'
// 忙碌状态自动回复默认文案
const busyDefault = '亲爱的顾客，欢迎光临小店。目前店内人手不足，可能无法及时回复，请您谅解，如急需帮助，请拨打店内电话。'
let allShopList = []
let globalConfig = {}

const editModalType = {
  /**
   * 首条消息1分钟自动回复
   */
  ONLINE_FIRST: 'online_first',
  /**
   * 忙碌状态自动回复
   */
  BUSY: 'busy'
}

export default {
  name: 'auto-reply',
  data() {
    return {
      editModalType,
      onlineFirst: {
        status: 0,
        content: ''
      },
      busy: {
        status: 0,
        content: ''
      },
      shopPopup: {
        show: true,
        searchValue: '',
        selectShop: {},
        shopList: []
      },
      editModal: {
        visible: false,
        type: editModalType.ONLINE_FIRST,
        content: ''
      }
    }
  },
  computed: {
    userInfo() {
      return store.getters.userInfo
    }
  },
  onLoad() {
    const { shopId, shops } = this.userInfo
    if (shopId === '0') {
      this.shopPopup.selectShop = shops?.[0] || {}
      allShopList = shops || []
      this.shopPopup.shopList = shops || []
    } else {
      this.shopPopup.selectShop = shops.find(item => item.id === `${shopId}`) || {}
    }
    this.getShopConfig()
  },
  methods: {
    /**
     * 显示/关闭弹窗
     */
    handlePopupVisible(visible) {
      if (visible && !this.shopPopup.shopList?.length) {
        return
      }
      this.shopPopup.show = visible
    },
    /**
     * 搜索门店
     */
    search() {
      const text = this.shopPopup.searchValue.trim()
      this.shopPopup.shopList = allShopList.filter(item => item.shopName.includes(text))
    },
    /**
     * 根据门店查询门店配置
     */
    getShopConfig(shop = undefined) {
      this.handlePopupVisible(false)
      if (shop) {
        this.shopPopup.selectShop = shop
      }
      const { id } = this.shopPopup.selectShop
      getShopsAutoReplyConfig(id).then(res => {
        const { data } = res
        if (!data?.config) {
          // 初始化
          this.setViewData()
          return
        }
        const config = JSON.parse(data.config)
        this.setViewData(config)
      }).catch(reason => {})
    },
    /**
     * 设置视图数据
     */
    setViewData(config = {}) {
      const {
        firstStatus = 0,
        firstContent = onlineFirstDefault,
        busyStatus = 0,
        busyContent = busyDefault
      } = config
      this.onlineFirst.status = firstStatus
      this.onlineFirst.content = firstContent
      this.busy.status = busyStatus
      this.busy.content = busyContent
      globalConfig = {
        ...config,
        firstStatus,
        firstContent,
        busyStatus,
        busyContent
      }
    },
    /**
     * 显示/隐藏编辑自动回复弹窗
     */
    handleEditModalVisible(visible = true, type = editModalType.ONLINE_FIRST) {
      if (!type) {
        this.editModal.visible = visible
        return
      }
      if (type === editModalType.ONLINE_FIRST) {
        this.editModal.content = this.onlineFirst.content
      } else {
        this.editModal.content = this.busy.content
      }
      this.editModal.type = type
      this.editModal.visible = visible
    },
    /**
     * 自动回复编辑弹窗确认
     */
    handleEditModalConfirm() {
      const { content, type } = this.editModal
      let text = content?.trim() || ''
      if (!text) {
        this.$toast('请填写自动回复内容')
        return
      }
      const config = { ...globalConfig }
      if (type === editModalType.ONLINE_FIRST) {
        config.firstContent = text
      } else {
        config.busyContent = text
      }
      this.saveAutoReplyConfig(config).then(res => {
        const { data } = res
        if (data) {
          this.setViewData(config)
          this.editModal.visible = false
        }
      }).catch(reason => {})
    },
    /**
     * 自动回复状态变化
     */
    handleStatusChange(value, type) {
      const config = { ...globalConfig }
      if (type === editModalType.ONLINE_FIRST) {
        config.firstStatus = value
      } else {
        config.busyStatus = value
      }
      this.saveAutoReplyConfig(config).then(res => {
        const { data } = res
        if (data) {
          this.setViewData(config)
          return
        }
        this.resetAutoReplyStatus(value, type)
      }).catch(reason => {
        this.resetAutoReplyStatus(value, type)
      })
    },
    /**
     * 操作失败状态复位
     */
    resetAutoReplyStatus(status, type) {
      let oStatus = status === 1 ? 0 : 1
      if (type === editModalType.ONLINE_FIRST) {
        this.onlineFirst.status = oStatus
      } else {
        this.busy.status = oStatus
      }
    },
    /**
     * 保存自动回复设置
     */
    saveAutoReplyConfig(config) {
      const { id } = this.shopPopup.selectShop
      return saveShopsAutoReplyConfig({
        shopId: id,
        config: JSON.stringify(config)
      })
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 0 24rpx 24rpx 24rpx;

  .header {
    padding: 24rpx 0;
    display: flex;

    view {
      color: #333333;
      line-height: 32rpx;
    }
    .oneline-hide {
      font-size: 30rpx;
      min-width: 0;
    }
    .iconfont {
      font-size: 32rpx;
      padding-left: 8rpx;
      flex-shrink: 0;
    }
  }

  .card {
    background-color: white;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-bottom: 24rpx;

    .header {
      display: flex;
      align-items: center;
      padding-top: 8rpx;
      padding-bottom: 24rpx;

      .title {
        flex: 1;
        font-size: 28rpx;
        color: #333333;
      }
    }
    .content {
      background: #F8F8F8;
      border-radius: 16rpx;
      padding: 24rpx;

      .text {
        font-size: 26rpx;
        color: #666666;
        line-height: 34rpx;
      }
      .action {
        margin-top: 20rpx;
        display: flex;
        justify-content: flex-end;

        .iconfont {
          font-size: 32rpx;
          padding-right: 16rpx;
        }
      }
    }
  }

  .shops-popup {
    padding: 0 24rpx 24rpx 24rpx;
    box-sizing: border-box;

    .header {
      color: #333333;
      font-size: 36rpx;
      font-weight: 500;
      line-height: 50rpx;
      display: flex;
      justify-content: center;
    }
    .search {
      width: 100%;
      display: flex;
      align-items: center;
      margin-top: 16rpx;
      border-radius: 12rpx;
      padding: 0 16rpx;
      box-sizing: border-box;
      background-color: rgba(0, 0, 0, 0.04);

      .iconfont {
        color: #999999;
        font-size: 32rpx;
        flex-shrink: 0;
        padding-right: 8rpx;
      }
      input {
        font-size: 28rpx;
        line-height: 40rpx;
        flex: 1;
        color: #333333;
        padding: 12rpx 0;
      }
    }
    .content {
      width: 100%;
      height: 55vh;
      margin-top: 12rpx;

      .shop-item {
        padding: 28rpx 0;
        font-size: 26rpx;
        color: #333333;
        line-height: 36rpx;
        border-bottom: 2rpx solid #eaeaea;
      }
    }
  }

  .edit-modal {
    width: 100%;
    padding: 24rpx;
    box-sizing: border-box;
  }
  .edit-modal textarea {
    width: 100%;
    height: 200rpx;
    font-size: 30rpx;
    padding: 24rpx;
    box-sizing: border-box;
    border: 2rpx solid #EEE;
  }
  .edit-modal view {
    font-size: 28rpx;
    color: #999999;
    margin: 16rpx 0;
  }
}
</style>
